<?php

namespace app\system\service;

use app\common\Random;
use app\system\validate\UserValidate;
use think\facade\Db;

class UserService
{
    /**
     * 查询条件组合
     * @param $postData
     * @return array
     * author:Wen
     */
    public function AndWhere($postData)
    {

        $where = [];
        if (!empty($postData['deptId'])) {
            $where[] = ['deptId', '=', $postData['deptId']];
        }
        if (!empty($postData['username'])) {
            $where[] = ['username', 'like', "%{$postData['username']}%"];
        }
        if (!empty($postData['phone'])) {
            $where[] = ['phone', 'like', "%{$postData['phone']}%"];
        }
        if (!empty($postData['status'])) {
            $where[] = ['status', '=', $postData['status']];
        }
        return $where;
    }

    /**
     * 查询用户列表
     * @param $request
     * @return array
     * author:wen
     */
    public function userList($request)
    {

        try {
            $pageSize = $request->post('pageSize');
            $where = $this->AndWhere($request->post());
            //分页
            $users = Db::name('user')
                ->where('deleteTime', 'null')  // 确保 deleteTime 字段为 NULL
                ->where($where)
                ->paginate([
                    'var_page' => 'currentPage',
                    'list_rows' => $pageSize,
                ])->each(function ($item, $key) {
                    $userDept = Db::name('department_user')->where('userId', $item['id'])->findOrEmpty();;
                    $item['dept'] = $userDept;
                    return $item;
                });
            return (['success' => true, 'info' => '查询成功!', 'data' => $users]);
        } catch (\Exception $e) {
            return (['success' => false, 'info' => $e->getMessage()]);
        }
    }

    /**
     * 删除用户(软删除)
     * @param $request
     * @return array
     * author:F
     */
    public function deleteUser($request)
    {
        $id = $request->delete('id');
        if (empty($id)) {
            return (['success' => false, 'info' => 'ID不能为空!']);
        }
        try {
            //软删除
            Db::name('user')
                ->where('id', $id)
                ->useSoftDelete('deleteTime', time())
                ->delete();
        } catch (\Exception $e) {
            return (['success' => false, 'info' => $e->getMessage()]);
        }
        return (['success' => true, 'info' => '删除成功!']);
    }

    /**
     * 更新用户
     * @param $request
     * @return array
     * author:wen
     */
    public function updateUser($request)
    {
        try {

            $updateData = $request->put();

            //验证
            $validate = new UserValidate();
            if (!$validate->scene('edit')->check($updateData)) {
                return (['success' => false, 'info' => $validate->getError()]);
            }
            unset($updateData['title']);
            unset($updateData['higherDeptOptions']);
            $updateData['deptId'] = $updateData['parentId'];
            if (!empty($updateData['parentId'])) {
                $departmentUserService = new DepartmentUserService();
                $departmentUserService->addDepartmentUser($updateData);
            }
            unset($updateData['parentId']);
            $updateData['updatedAt'] = date("Y-m-d H:i:s");
            Db::name('user')
                ->save($updateData);
        } catch (\Exception $e) {
            return (['success' => false, 'info' => $e->getMessage()]);
        }
        return (['success' => true, 'info' => '更新成功!']);
    }

    /**
     * 变更用户状态
     * @param $request
     * @return array
     * author:F
     */
    public function updateStatus($request)
    {
        try {
            $updateData = $request->put();
            //验证
            $validate = new UserValidate();
            if (!$validate->scene('status')->check($updateData)) {
                return (['success' => false, 'info' => $validate->getError()]);
            }
            unset($updateData['title']);
            $updateData['updatedAt'] = date("Y-m-d H:i:s");
            Db::name('user')
                ->save($updateData);
        } catch (\Exception $e) {
            return (['success' => false, 'info' => $e->getMessage()]);
        }
        return (['success' => true, 'info' => '更新成功!']);
    }

    /**
     * 保存(新增)用户
     * @param $request
     * @return array
     * author:F
     */
    public function saveUser($request)
    {
        //开启事务
        Db::startTrans();
        try {
            $saveData = $request->post();

            //验证
            $validate = new UserValidate();

            if (!$validate->check($saveData)) {
                return (['success' => false, 'info' => $validate->getError()]);
            }
            $saveData['salt'] = Random::alnum();
            $saveData['password'] = md5(md5($saveData['password']) . $saveData['salt']);
//            $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
            unset($saveData['title']);
            $updateData['deptId'] = $saveData['parentId'];
            unset($updateData['parentId']);
            $saveData['createdAt'] = date("Y-m-d H:i:s");
            Db::name('user')
                ->save($saveData);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return (['success' => false, 'info' => $e->getMessage()]);
        }
        return (['success' => true, 'info' => '保存成功!']);
    }

    public function resetPassword($request)
    {
        //开启事务
        Db::startTrans();
        try {
            $saveData = $request->post();
            if (empty($saveData['password'])) {
                $saveData['password'] = 'Thinkbay@123456';

            }
            $password=$saveData['password'];
            //验证
            $validate = new UserValidate();
            if (!$validate->scene('resetPassword')->check($saveData)) {
                return (['success' => false, 'info' => $validate->getError()]);
            }
            $saveData['salt'] = Random::alnum();
            $saveData['password'] = md5(md5($saveData['password']) . $saveData['salt']);
//            $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
            $saveData['createdAt'] = date("Y-m-d H:i:s");
            Db::name('user')
                ->save($saveData);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return (['success' => false, 'info' => $e->getMessage()]);
        }
        return (['success' => true, 'info' =>  $password]);
    }

}